package vn.bk.hotel;

import hust.sig.api.service.ImplementHotelService;
import hust.sig.api.service.model.FullDataInstance;
import hust.sig.api.service.model.SimpleDataObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.MenuItem.OnMenuItemClickListener;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.GoogleMap.OnCameraChangeListener;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;

import vn.bk.hotel.adapter.DatabaseHotel;
import vn.bk.hotel.adapter.ListHotelAdapter;
import vn.bk.hotel.global.Language;
import vn.bk.hotel.global.Service;
import vn.bk.hotel.map.JSONParser;
import vn.bk.hotel.object.HotelInfo;
import vn.bk.hotel.utils.Convert;
import vn.bk.hotel.utils.MapUtils;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.DataSetObserver;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.RatingBar;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class ListHotel extends BaseActivity {

    private ListView myListViewResult;
    private ListHotelAdapter myAdapter;

    private ArrayList<HotelInfo> myListHotel;

    boolean loadingMore = false;
    int itemsPerPage = 10;

    public static SimpleDataObject dataObject;

    public static final int SEARCH_BY_LOCATION = 0;
    public static final int SEARCH_BY_DISTRICT = 1;
    public static final int SEARCH_BY_LANDMARK = 2;
    public static final int VIEW_ALL = Menu.FIRST + 4;
    public static int typeSearch;
    public static float distance;
    public static int numberStar;
    public static String uriType = "http://hust.se.vtio.owl#Hotel";
    private int offsetLocation = 0;
    private int offsetDistrict = 0;
    public static String keyWord;

    public static double latitude, longitude;
    public static float radius;
    // private GetListHotel getListHotel;
    private boolean endSearch = false;
    private final int offsetAdd = 10;
    private final int limit = 8;
    private TextView textNote;
    View footerView;

    private Button sort;

    private boolean viewMap = false;

    // Init for map

    private View mapView;
    private GoogleMap mMap;
    private ArrayList<MarkerHotel> allMarker;
    private LatLngBounds.Builder bc;
    // private final String TAG = "ViewALlOnMap";
    private View infoWindowView;
    private TextView name, address;
    private RatingBar ratingBar;
    private LinearLayout frameLayout;
    private DatabaseHotel myDB;
    private ImageView road, call, favorite;

    private int typeFilter = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	// TODO A 0 uto-generated method stub
	super.onCreate(savedInstanceState);
	setContentView(R.layout.result);
	myListHotel = new ArrayList<HotelInfo>();
	getWindow().setSoftInputMode(
		WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
	init();

	myAdapter = new ListHotelAdapter(this, myListHotel);

	footerView = ((LayoutInflater) this
		.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
		R.layout.listfooter, null, false);
	myListViewResult.addFooterView(footerView);
	// myListViewResult.setOnItemClickListener(this);
	myListViewResult.setAdapter(myAdapter);
	//
	// getSupportActionBar().setHomeButtonEnabled(true);
	// getSupportActionBar().setDisplayHomeAsUpEnabled(true);

	myListViewResult.setOnScrollListener(new OnScrollListener() {

	    @Override
	    public void onScrollStateChanged(AbsListView view, int scrollState) {
	    }

	    @Override
	    public void onScroll(AbsListView view, int firstVisibleItem,
		    int visibleItemCount, int totalItemCount) {
		// TODO Auto-generated method stub
		// what is the bottom iten that is visible
		int lastInScreen = firstVisibleItem + visibleItemCount;

		// is the bottom item visible & not loading more already ? Load
		// more !
		if ((lastInScreen == totalItemCount) && !(loadingMore)
			&& !endSearch) {
		    endSearch = true;
		    new Thread(loadMoreListItems).start();
		}
	    }
	});

    }

    private Runnable loadMoreListItems = new Runnable() {
	@Override
	public void run() {
	    // Set flag so we cant load new items 2 at the same time
	    loadingMore = true;

	    // Reset the array that holds the new items
	    myListHotel = new ArrayList<HotelInfo>();

	    // Simulate a delay, delete this on a production environment!
	    try {
		Thread.sleep(500);
	    } catch (InterruptedException e) {
	    }
	    if (typeSearch == SEARCH_BY_DISTRICT) {
		offsetDistrict += offsetAdd;
	    } else {
		offsetLocation += offsetAdd;
	    }

	    runOnUiThread(returnRes);

	}
    };

    // Since we cant update our UI from a thread this Runnable takes care of
    // that!
    private Runnable returnRes = new Runnable() {
	@Override
	public void run() {

	    new GetListHotel(ListHotel.this).execute("find");

	}
    };

    private void init() {
	// TODO Auto-generated method stub
	myListViewResult = (ListView) findViewById(R.id.listResult);
	myListViewResult.setFastScrollEnabled(true);
	// filter = (EditText) findViewById(R.id.et_filter);
	textNote = (TextView) findViewById(R.id.text_note);

	sort = (Button) findViewById(R.id.bt_sort);

	final Button filter = (Button) findViewById(R.id.bt_filter);
	filter.setOnClickListener(new OnClickListener() {

	    @Override
	    public void onClick(View v) {
		// TODO Auto-generated method stub
		showDialogFilter();
	    }
	});
	mapView = (View) findViewById(R.id.view_all_map_layout);
	mapView.setVisibility(View.GONE);
	addMap();
	final ImageView viewMode = (ImageView) findViewById(R.id.img_view_all_map);
	viewMode.setOnClickListener(new OnClickListener() {

	    @Override
	    public void onClick(View v) {
		Log.i("tag", "Change mode view");
		if (viewMap) {
		    Animation animation = AnimationUtils.loadAnimation(
			    getBaseContext(), R.anim.transition_left_to_right);
		    animation.setStartOffset(0);
		    myListViewResult.startAnimation(animation);
		    mapView.setVisibility(View.GONE);
		    viewMap = false;
		    sort.setClickable(true);
		    viewMode.setImageResource(android.R.drawable.ic_dialog_map);
		    sort.setBackgroundResource(R.drawable.bt_menu_list);
		} else {
		    if (myAdapter.getListHotel().size() > 0) {
			Animation animation = AnimationUtils.loadAnimation(
				getBaseContext(),
				R.anim.transition_right_to_left);
			animation.setStartOffset(0);
			mapView.startAnimation(animation);
			mapView.setVisibility(View.VISIBLE);
			sort.setClickable(false);
			viewMap = true;
			updateMap(myAdapter.getListHotel());
			viewMode.setImageResource(R.drawable.list);
			sort.setBackgroundResource(R.drawable.bt_menu_list_disable);
		    }
		}
	    }
	});
	initPopup();

    }

    private void updateMap(ArrayList<HotelInfo> listChange) {
	Log.i("Size of list before switch map",
		String.valueOf(myListHotel.size()));
	mMap.clear();
	bc = new LatLngBounds.Builder();
	LatLng myPoint = new LatLng(SplashScreen.latitude,
		SplashScreen.longtitude);
	if (typeSearch == ListHotel.SEARCH_BY_LOCATION) {
	    bc.include(myPoint);
	    mMap.addMarker(new MarkerOptions().position(myPoint)
		    .title("My Location")
		    .icon(BitmapDescriptorFactory.fromResource(R.drawable.me)));
	}
	for (int i = 0; i < listChange.size(); i++) {
	    HotelInfo myHotel = listChange.get(i);
	    LatLng myPoint1 = new LatLng(myHotel.getLatitude(),
		    myHotel.getLongitude());

	    Marker marker = mMap.addMarker(new MarkerOptions().position(
		    myPoint1).icon(
		    BitmapDescriptorFactory
			    .fromResource(R.drawable.map_pin_normal)));

	    allMarker.add(new MarkerHotel(marker, i));
	    bc.include(myPoint1);

	}

	final CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngBounds(
		bc.build(), 45);
	mMap.setOnCameraChangeListener(new OnCameraChangeListener() {

	    @Override
	    public void onCameraChange(CameraPosition arg0) {
		// TODO Auto-generated method stub
		mMap.moveCamera(cameraUpdate);
		mMap.animateCamera(cameraUpdate);
		mMap.setOnCameraChangeListener(null);
	    }
	});

	initMap();
    }

    private void addMap() {
	myDB = new DatabaseHotel(getApplicationContext());

	allMarker = new ArrayList<MarkerHotel>();
	mMap = ((SupportMapFragment) getSupportFragmentManager()
		.findFragmentById(R.id.map)).getMap();

	frameLayout = (LinearLayout) mapView.findViewById(R.id.layout_overlay);

	initActionMenu();
	bc = new LatLngBounds.Builder();
	LatLng myPoint = new LatLng(SplashScreen.latitude,
		SplashScreen.longtitude);
	if (typeSearch == ListHotel.SEARCH_BY_LOCATION) {
	    bc.include(myPoint);
	    mMap.addMarker(new MarkerOptions().position(myPoint)
		    .title("My Location")
		    .icon(BitmapDescriptorFactory.fromResource(R.drawable.me)));
	}

	initMap();

    }

    private void initMap() {
	mMap.setOnMapClickListener(new OnMapClickListener() {

	    @Override
	    public void onMapClick(LatLng arg0) {
		// TODO Auto-generated method stub
		removeView();
	    }
	});

	mMap.setOnMarkerClickListener(new OnMarkerClickListener() {

	    @Override
	    public boolean onMarkerClick(Marker marker) {
		// TODO Auto-generated method stub
		for (int i = 0; i < allMarker.size(); i++) {
		    if (allMarker.get(i).getMarker().getId()
			    .equals(marker.getId())) {
			addView(myAdapter.getListHotel().get(
				allMarker.get(i).getPosition()));
			break;
		    }
		}
		return false;
	    }
	});
    }

    private void filtByName(String keys, int type) {
	if (myAdapter.getCount() > 0) {

	    if (!keys.trim().equals("")) {
		ArrayList<HotelInfo> listFilter = new ArrayList<HotelInfo>();

		myListViewResult.removeFooterView(footerView);
		for (int i = 0; i < myAdapter.getListHotel().size(); i++) {

		    String target;
		    if (typeFilter == 0) {

			target = Convert.convertRoute(myAdapter.getListHotel()
				.get(i).getAdress().toLowerCase());
		    } else {

			target = Convert.convertRoute(myAdapter.getListHotel()
				.get(i).getNameHotel().toLowerCase());
		    }
		    Log.i("search", target);
		    if (!target.replace(Convert.convertRoute(keys), "").equals(
			    target)) {
			listFilter.add(myListHotel.get(i));
			Log.i("filtered", target);
		    }

		}

		myListViewResult.setAdapter(new ListHotelAdapter(
			ListHotel.this, listFilter));
		updateMap(listFilter);
		myListViewResult.removeFooterView(footerView);
		endSearch = true;
	    } else {
		endSearch = false;

		myListViewResult.addFooterView(footerView);
		myListViewResult.setAdapter(myAdapter);
		updateMap(myAdapter.getListHotel());
	    }

	}
    }

    private void showDialogFilter() {
	View view = View.inflate(this, R.layout.filt, null);
	AlertDialog.Builder dialog = new AlertDialog.Builder(this);
	final EditText textFilt = (EditText) view.findViewById(R.id.et_filter);
	Spinner sp = (Spinner) view.findViewById(R.id.sp_change_filt);
	sp.setAdapter(new ArrayAdapter<String>(this,
		android.R.layout.simple_spinner_dropdown_item, new String[] {
			getString(R.string.filt_by_address),
			getString(R.string.filt_by_name) }));

	sp.setOnItemSelectedListener(new OnItemSelectedListener() {

	    @Override
	    public void onItemSelected(AdapterView<?> parent, View view,
		    int position, long id) {
		typeFilter = position;
	    }

	    @Override
	    public void onNothingSelected(AdapterView<?> parent) {
		typeFilter = 0;
	    }
	});
	dialog.setTitle(getString(R.string.announce));
	dialog.setView(view);
	dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {

	    @Override
	    public void onClick(DialogInterface dialog, int which) {
		String fil = textFilt.getText().toString().trim().toLowerCase();

		filtByName(fil, typeFilter);

	    }
	});
	dialog.show();
    }

    private void initPopup() {
	final PopupMenu popupSort = new PopupMenu(this, sort);

	if (typeSearch == SEARCH_BY_LOCATION)
	    popupSort.inflate(R.menu.sort_menu);
	else
	    popupSort.inflate(R.menu.sort_menu_no_radius);
	sort.setOnClickListener(new OnClickListener() {

	    @Override
	    public void onClick(View v) {
		if (!mapView.isShown()) {
		    popupSort.show();
		}
	    }
	});

	popupSort
		.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {

		    @Override
		    public boolean onMenuItemClick(android.view.MenuItem item) {
			// TODO Auto-generated method stub
			switch (item.getItemId()) {
			case R.id.sort_rating:
			    HotelInfo[] arrayHotel = new HotelInfo[myAdapter
				    .getListHotel().size()];
			    arrayHotel = myAdapter.getListHotel().toArray(
				    arrayHotel);
			    Arrays.sort(arrayHotel, new MyCompare());
			    ArrayList<HotelInfo> list = new ArrayList<HotelInfo>(
				    Arrays.asList(arrayHotel));
			    myAdapter.clear();
			    for (int j = 0; j < list.size(); j++) {
				myAdapter.addItem(list.get(j));
			    }
			    myAdapter.notifyDataSetChanged();
			    break;
			case R.id.sort_radius:
			    HotelInfo[] arrayHotel2 = new HotelInfo[myAdapter
				    .getListHotel().size()];
			    arrayHotel2 = myAdapter.getListHotel().toArray(
				    arrayHotel2);
			    Arrays.sort(arrayHotel2, new MyCompareRadius());
			    ArrayList<HotelInfo> list2 = new ArrayList<HotelInfo>(
				    Arrays.asList(arrayHotel2));
			    myAdapter.clear();
			    for (int j = 0; j < list2.size(); j++) {
				myAdapter.addItem(list2.get(j));
			    }
			    myAdapter.notifyDataSetChanged();
			    break;
			}
			return true;
		    }
		});
    }

    public class GetListHotel extends AsyncTask<String, Integer, String> {

	FullDataInstance[] fullDataInstances = null;
	private boolean location = true;
	private Context mContext;

	public GetListHotel(Context context) {
	    // allUri = context.getResources().getStringArray(R.array.type_uri);
	    this.mContext = context;
	}

	@Override
	protected void onPreExecute() {
	    // TODO Auto-generated method stub
	    super.onPreExecute();
	    textNote.setVisibility(TextView.INVISIBLE);

	}

	@Override
	protected String doInBackground(String... params) {
	    // TODO Auto-generated method stub
	    switch (typeSearch) {
	    case SEARCH_BY_DISTRICT:
		location = false;

		try {
		    fullDataInstances = Service.getHotelService()
			    .getAllHotelOfDistrict(uriType,
				    dataObject.getUriString(),
				    Language.getLanguage(mContext), limit,
				    offsetDistrict);
		} catch (Exception e) {
		}

		break;
	    case SEARCH_BY_LOCATION:

		try {
		    if (!uriType.equals("http://hust.se.vtio.owl#Hotel")
			    || numberStar == 0) {

			Log.i("finding", "not search hotel");
			fullDataInstances = Service.getHotelService()
				.getAllHotelByLocation(SplashScreen.longtitude,
					SplashScreen.latitude, distance,
					uriType, keyWord, limit,
					offsetLocation,
					ImplementHotelService.VIETNAMESE);
		    } else {
			Log.i("finding", "search hotel");
			fullDataInstances = Service.getHotelService()
				.getHotelWithLocationAndRating(numberStar,
					SplashScreen.longtitude,
					SplashScreen.latitude, distance,
					Language.getLanguage(mContext), limit,
					offsetLocation);
		    }

		} catch (Exception e) {
		    // TODO: handle exception
		}

		break;

	    case SEARCH_BY_LANDMARK:
		location = false;
		try {
		    if (!uriType.equals("http://hust.se.vtio.owl#Hotel")
			    || numberStar == 0) {

			fullDataInstances = Service.getHotelService()
				.getAllHotelByLocation(longitude, latitude,
					radius, uriType, keyWord, limit,
					offsetLocation,
					Language.getLanguage(mContext));
		    } else {
			fullDataInstances = Service.getHotelService()
				.getHotelWithLocationAndRating(numberStar,
					longitude, latitude, radius,
					Language.getLanguage(mContext), limit,
					offsetLocation);
		    }
		} catch (Exception e) {
		    // TODO: handle exception
		}
		break;
	    }
	    ViewMap.isDirection = location;
	    return null;
	}

	@Override
	protected void onPostExecute(String result) {
	    if (fullDataInstances != null) {
		if (fullDataInstances.length == 0) {
		    runOnUiThread(new Runnable() {
			@Override
			public void run() {
			    // TODO Auto-generated method stub
			    myListViewResult.removeFooterView(footerView);
			    if (myAdapter.getListHotel().size() == 0) {
				textNote.setVisibility(TextView.VISIBLE);
				textNote.setText(getString(R.string.search_unavaiable));
			    }
			}
		    });
		} else {
		    textNote.setVisibility(TextView.INVISIBLE);
		    for (int i = 0; i < fullDataInstances.length; i++) {
			FullDataInstance data = fullDataInstances[i];
			Log.i("URI", data.getUri());
			// if (isRecommend(data.getUri())) {

			myListHotel.add(new HotelInfo(data.getLabel(), data
				.getType(), data.getAddress(), data
				.getRatingNum(), data.getImageURL(), data
				.getLongitude(), data.getLatitude(), data
				.getPhone(), data.getUri(), data
				.getAbstractInfo(), location));
			// }
		    }
		    for (int j = 0; j < myListHotel.size(); j++) {
			myAdapter.addItem(myListHotel.get(j));
		    }
		    myAdapter.notifyDataSetChanged();
		    loadingMore = false;
		    endSearch = false;
		}
	    } else {
		Toast.makeText(ListHotel.this,
			getString(R.string.error_connect), Toast.LENGTH_SHORT)
			.show();
		runOnUiThread(new Runnable() {

		    @Override
		    public void run() {
			// TODO Auto-generated method stub
			myListViewResult.removeFooterView(footerView);
		    }
		});
		endSearch = true;
	    }

	    super.onPostExecute(result);
	}
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
	// TODO Auto-generated method stub
//	MenuInflater inflater = getSupportMenuInflater();
//	inflater.inflate(R.menu.search_bar, menu);
//
//	MenuItem refresh = menu.findItem(R.id.action_refresh);
//	refresh.setOnMenuItemClickListener(new OnMenuItemClickListener() {
//
//	    @Override
//	    public boolean onMenuItemClick(MenuItem item) {
//
//		if (!endSearch) {
//		    offsetDistrict = 0;
//		    offsetLocation = 0;
//		    myAdapter.clear();
//		    myAdapter.notifyDataSetChanged();
//		    new Thread(loadMoreListItems).start();
//		}
//		return false;
//	    }
//	});

	return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
	// TODO Auto-generated method stub

	return super.onOptionsItemSelected(item);
    }

    protected boolean isAlwaysExpanded() {
	return false;
    }

    class MyCompare implements Comparator<HotelInfo> {

	@Override
	public int compare(HotelInfo lhs, HotelInfo rhs) {

	    return rhs.getNumRate() - lhs.getNumRate();
	}

    }

    class MyCompareRadius implements Comparator<HotelInfo> {

	@Override
	public int compare(HotelInfo lhs, HotelInfo rhs) {

	    return (int) (lhs.getRadius() * 1000 - rhs.getRadius() * 1000);
	}

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
	// TODO Auto-generated method stub
	if (keyCode == KeyEvent.KEYCODE_BACK) {
	    if (viewMap && infoWindowView.isShown()) {
		removeView();
	    } else {
		finish();
	    }
	}
	return false;
    }

    // Map actions
    private void initActionMenu() {
	LayoutInflater inflater = (LayoutInflater) getApplicationContext()
		.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	infoWindowView = inflater.inflate(R.layout.overlay, null);
	name = (TextView) infoWindowView.findViewById(R.id.name_hotel_map);
	address = (TextView) infoWindowView
		.findViewById(R.id.address_hotel_map);
	ratingBar = (RatingBar) infoWindowView
		.findViewById(R.id.rating_hotel_map);
	road = (ImageView) infoWindowView.findViewById(R.id.img_action_road);
	call = (ImageView) infoWindowView.findViewById(R.id.img_action_call);
	favorite = (ImageView) infoWindowView
		.findViewById(R.id.img_action_add_favorite);
	if (ListHotel.typeSearch == ListHotel.SEARCH_BY_LOCATION) {
	    road.setImageResource(R.drawable.road_map);
	} else {
	    road.setImageResource(R.drawable.road_disable_map);
	}

    }

    private void addView(final HotelInfo hotel) {
	// if (infoWindowView == null) {
	name.setText(hotel.getNameHotel());
	address.setText(hotel.getAdress());
	ratingBar.setRating(hotel.getNumRate());
	if (myDB.isExistInDatabase(hotel)) {
	    favorite.setImageResource(R.drawable.favorite_map);
	} else {
	    favorite.setImageResource(R.drawable.favorite_disable_map);
	}
	road.setOnClickListener(new OnClickListener() {

	    @Override
	    public void onClick(View v) {

		if (ListHotel.typeSearch == ListHotel.SEARCH_BY_LOCATION) {
		    removeView();
		    new ConnectAsyncTask(MapUtils.makeURL(
			    SplashScreen.latitude, SplashScreen.longtitude,
			    hotel.getLatitude(), hotel.getLongitude()))
			    .execute();
		}
	    }
	});
	call.setOnClickListener(new OnClickListener() {

	    @Override
	    public void onClick(View v) {
		removeView();
		Intent localIntent = new Intent("android.intent.action.DIAL",
			Uri.parse("tel:" + hotel.getPhone()));
		startActivity(localIntent);
	    }
	});
	favorite.setOnClickListener(new OnClickListener() {

	    @Override
	    public void onClick(View v) {
		if (myDB.isExistInDatabase(hotel)) {
		    favorite.setImageResource(R.drawable.favorite_disable_map);
		    myDB.deleteHotel(hotel);
		} else {
		    favorite.setImageResource(R.drawable.favorite_map);
		    myDB.createHotel(hotel);
		}
	    }
	});

	frameLayout.addView(infoWindowView);

	Animation animation = AnimationUtils.loadAnimation(getBaseContext(),
		R.anim.transition_bottom_to_top);
	animation.setStartOffset(0);
	infoWindowView.startAnimation(animation);

    }

    private void updateMarker() {
	if (ListHotel.typeSearch == ListHotel.SEARCH_BY_LOCATION) {
	    LatLng myPoint = new LatLng(SplashScreen.latitude,
		    SplashScreen.longtitude);
	    mMap.addMarker(new MarkerOptions().position(myPoint)
		    .title("My Location")
		    .icon(BitmapDescriptorFactory.fromResource(R.drawable.me)));
	}
	allMarker = new ArrayList<MarkerHotel>();
	for (int i = 0; i < myListHotel.size(); i++) {
	    HotelInfo myHotel = myListHotel.get(i);
	    LatLng myPoint1 = new LatLng(myHotel.getLatitude(),
		    myHotel.getLongitude());

	    Marker marker = mMap.addMarker(new MarkerOptions().position(
		    myPoint1).icon(
		    BitmapDescriptorFactory
			    .fromResource(R.drawable.map_pin_normal)));

	    allMarker.add(new MarkerHotel(marker, i));

	}
    }

    private void removeView() {
	if (infoWindowView.isShown())
	    frameLayout.removeView(infoWindowView);
	Animation animation = AnimationUtils.loadAnimation(getBaseContext(),
		R.anim.transition_top_to_bottom_out);
	animation.setStartOffset(0);
	infoWindowView.startAnimation(animation);

    }

    public void drawPath(String result) {

	try {
	    // Tranform the string into a json object
	    final JSONObject json = new JSONObject(result);
	    JSONArray routeArray = json.getJSONArray("routes");
	    JSONObject routes = routeArray.getJSONObject(0);
	    JSONObject overviewPolylines = routes
		    .getJSONObject("overview_polyline");
	    String encodedString = overviewPolylines.getString("points");
	    List<LatLng> list = MapUtils.decodePoly(encodedString);

	    // updateMarker();
	    updateMap(myAdapter.getListHotel());
	    for (int z = 0; z < list.size() - 1; z++) {
		LatLng src = list.get(z);
		LatLng dest = list.get(z + 1);
		mMap.addPolyline(new PolylineOptions()
			.add(new LatLng(src.latitude, src.longitude),
				new LatLng(dest.latitude, dest.longitude))
			.width(8).color(Color.RED).geodesic(true));
	    }

	} catch (JSONException e) {

	}
    }

    private class ConnectAsyncTask extends AsyncTask<Void, Void, String> {
	private ProgressDialog progressDialog;
	String url;

	ConnectAsyncTask(String urlPass) {
	    url = urlPass;
	}

	@Override
	protected void onPreExecute() {
	    // TODO Auto-generated method stub
	    super.onPreExecute();
	    progressDialog = new ProgressDialog(ListHotel.this);
	    progressDialog.setMessage(getString(R.string.find_route));
	    progressDialog.setIndeterminate(true);
	    progressDialog.show();
	}

	@Override
	protected String doInBackground(Void... params) {
	    JSONParser jParser = new JSONParser();
	    String json = jParser.getJSONFromUrl(url);
	    return json;
	}

	@Override
	protected void onPostExecute(String result) {
	    super.onPostExecute(result);
	    progressDialog.dismiss();
	    if (result != null) {
		drawPath(result);
	    }
	}
    }

    class MarkerHotel {
	private Marker marker;
	private int position;

	public MarkerHotel(Marker marker, int position) {
	    this.marker = marker;
	    this.position = position;
	}

	public Marker getMarker() {
	    return marker;
	}

	public int getPosition() {
	    return position;
	}

    }

}
